package com.yyk.yykywd.ui;

import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.yyk.yykywd.BusinessPeopleInfoKt;
import com.yyk.yykywd.CheckUpdateUtils;
import com.yyk.yykywd.R;
import com.yyk.yykywd.base.BaseActivity;
import com.yyk.yykywd.config.HttpUrl;
import com.yyk.yykywd.http.ApiService;
import com.yyk.yykywd.listenter.DialogSureCancelListenter;
import com.yyk.yykywd.mvvm.entity.APPInfo;
import com.yyk.yykywd.mvvm.ui.fragment.NewCustomerFragment;
import com.yyk.yykywd.mvvm.ui.fragment.NewHomeFragment;
import com.yyk.yykywd.ui.home.fragment.HomeFragment;
import com.yyk.yykywd.ui.login.LoginActivity;
import com.yyk.yykywd.ui.mine.fragment.MineFragment;
import com.yyk.yykywd.mvvm.ui.fragment.NewWorkFragment;
import com.yyk.yykywd.util.DialogUtil;
import com.yyk.yykywd.util.FileUtils;
import com.yyk.yykywd.util.Md5Util2;
import com.yyk.yykywd.util.ToastUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class MainActivity extends BaseActivity {
    public static final String TAG = "MainActivity";

    @BindView(R.id.mMain_rb_iv)
    ImageView mMainRbIv;
    @BindView(R.id.mMain_rb_tv)
    TextView mMainRbTv;
    @BindView(R.id.mMain_rb)
    LinearLayout mMainRb;
    @BindView(R.id.mMain_rb_iv2)
    ImageView mMainRbIv2;
    @BindView(R.id.mMain_rb_tv2)
    TextView mMainRbTv2;
    @BindView(R.id.mMain_rb2)
    LinearLayout mMainRb2;
    @BindView(R.id.mMain_rb_iv3)
    ImageView mMainRbIv3;
    @BindView(R.id.mMain_rb_tv3)
    TextView mMainRbTv3;
    @BindView(R.id.mMain_rb3)
    LinearLayout mMainRb3;
    @BindView(R.id.mMain_rb_iv4)
    ImageView mMainRbIv4;
    @BindView(R.id.mMain_rb_tv4)
    TextView mMainRbTv4;
    @BindView(R.id.mMain_rb4)
    LinearLayout mMainRb4;
    private FragmentManager fragmentManager;
    private NewHomeFragment homeFragment;
    private NewWorkFragment workFragment;
    private NewCustomerFragment customerFragment;
    private MineFragment mineFragment;

    private APPInfo info;
    private Dialog dialog;

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initView() {
        initTooblar();
        initFragment();

        checkUpdate();
    }

    /**
     * 访问网络获取到服务器的版本号
     */
    public void checkUpdate() {
        Map<String, String> map = new TreeMap<>();
        map.put("type", "2");
        map.put("device", "1");
        map.put("sign", Md5Util2.createSign(map));
        ApiService.getInstance().api.postVersion(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Observer<APPInfo>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(APPInfo info) {
                        if (info.getCode() == 1) {
                            MainActivity.this.info = info;
                            try {
                                int version_code = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
                                if (info.getData().getVcode() > version_code) {
                                    dialog = CheckUpdateUtils.showUpdateDialog(mActivity, info, () -> {
                                        MainActivityPermissionsDispatcher.updateWithPermissionCheck(MainActivity.this);
                                    });
                                }
                            } catch (PackageManager.NameNotFoundException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public void initData() {
        Hawk.put("ISLOGFLAG", TAG);
    }

    private void initTooblar() {
        hidetoolBar();

    }

    private void initFragment() {
        fragmentManager = getSupportFragmentManager();
        homeFragment = new NewHomeFragment();
        workFragment = new NewWorkFragment();
        customerFragment = new NewCustomerFragment();
        mineFragment = new MineFragment();
        switchFragment(homeFragment, NewHomeFragment.TAG);
    }

    /**
     * 选择Fragment
     *
     * @param fragment
     * @param tag
     */
    public void switchFragment(Fragment fragment, String tag) {
        hideFragment();
        if (fragmentManager == null || fragment == null) {
            return;
        }
        FragmentTransaction tion = fragmentManager.beginTransaction();
        Fragment fragmentByTag = fragmentManager.findFragmentByTag(tag);
        if (fragmentByTag == null) {
            tion.add(R.id.main_frame, fragment, tag);
        }
        tion.show(fragment);
        tion.commit();
    }

    /**
     * 隐藏Fragment
     */
    private void hideFragment() {
        if (fragmentManager == null)
            return;
        FragmentTransaction tion = fragmentManager.beginTransaction();
        if (homeFragment != null)
            tion.hide(homeFragment);
        if (workFragment != null)
            tion.hide(workFragment);
        if (customerFragment != null)
            tion.hide(customerFragment);
        if (mineFragment != null)
            tion.hide(mineFragment);
        tion.commit();
    }


    private void clearPitcureColor() {
        mMainRbTv.setTextColor(getResources().getColor(R.color.gray_aa));
        mMainRbIv.setImageResource(R.drawable.icon_sy_off);

        mMainRbTv2.setTextColor(getResources().getColor(R.color.gray_aa));
        mMainRbIv2.setImageResource(R.drawable.icon_gz_off);

        mMainRbTv3.setTextColor(getResources().getColor(R.color.gray_aa));
        mMainRbIv3.setImageResource(R.drawable.icon_wd_kh);

        mMainRbTv4.setTextColor(getResources().getColor(R.color.gray_aa));
        mMainRbIv4.setImageResource(R.drawable.icon_wd_off);
    }

    /**
     * 1.首页
     * 2.工作室
     * 3.快捷
     * 4.患者
     * 5.我的
     *
     * @param view
     */
    @OnClick({R.id.mMain_rb, R.id.mMain_rb2, R.id.mMain_rb3, R.id.mMain_rb4})
    public void onViewClicked(View view) {

        switch (view.getId()) {
            case R.id.mMain_rb:
                switchFragment(homeFragment, NewHomeFragment.TAG);
                clearPitcureColor();
                mMainRbTv.setTextColor(getResources().getColor(R.color.blue_51));
                mMainRbIv.setImageResource(R.drawable.icon_sy_on);
                break;
            case R.id.mMain_rb2:
                switchFragment(workFragment, NewWorkFragment.TAG);
                clearPitcureColor();
                mMainRbTv2.setTextColor(getResources().getColor(R.color.blue_51));
                mMainRbIv2.setImageResource(R.drawable.icon_work_on);

                break;
            case R.id.mMain_rb3:
                switchFragment(customerFragment, NewCustomerFragment.TAG);
                clearPitcureColor();
                mMainRbTv3.setTextColor(getResources().getColor(R.color.blue_51));
                mMainRbIv3.setImageResource(R.drawable.icon_kh_on);
                break;
            case R.id.mMain_rb4:
                switchFragment(mineFragment, MineFragment.TAG);
                clearPitcureColor();
                mMainRbTv4.setTextColor(getResources().getColor(R.color.blue_51));
                mMainRbIv4.setImageResource(R.drawable.icon_wd_on);
                break;

        }
    }

    /**
     * Android 连续点击返回键退出程序 - QiY6010的博客 - CSDN博客  https://blog.csdn.net/QiY6010/article/details/77468385
     */
    //记录用户首次点击返回键的时间
    private long firstTime = 0;

    //连续点击两次退出程序
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
            long secondTime = System.currentTimeMillis();
            if (secondTime - firstTime > 2000) {
                ToastUtil.showShort(mActivity, "再按一次退出程序");
                firstTime = secondTime;
                return true;
            } else {
//                System.exit(0);
            }
        }
        return super.onKeyUp(keyCode, event);
    }


    private NotificationManager mNotifyManager;
    private NotificationCompat.Builder mBuilder;
    private int id = 1;
    private int preProgress = 0;
    //通知栏跳转Intent
    private PendingIntent updatePendingIntent = null;

    /**
     * 下载最新的安装包
     */
    private void updateAPK(final APPInfo updateInfo) {
        new Thread(() -> {
            try {
                long totalSize;// 文件总大小
                long downloadCount = 0;// 已经下载好的大小
                String path;
                // 下载apk，并且安装
                File file = FileUtils.getFile("yykywd.apk");

                URL url = new URL(HttpUrl.BASE_URL + updateInfo.getData().getUrl());
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setConnectTimeout(10 * 1000);
                httpURLConnection.setReadTimeout(10 * 1000);
                httpURLConnection.setDoInput(true);
                // 获取下载文件的size
                httpURLConnection.setRequestProperty("Accept-Encoding", "identity");
                totalSize = httpURLConnection.getContentLength();
                Logger.e("获取文件的大小" + totalSize);
                int response = httpURLConnection.getResponseCode(); //获得服务器的响应码
                if (response == HttpURLConnection.HTTP_OK) {//200
                    InputStream inputStream = httpURLConnection.getInputStream();
                    FileOutputStream outputStream = new FileOutputStream(file, false);// 文件存在则覆盖掉
                    byte buffer[] = new byte[1024];
                    int readsize = 0;
                    while ((readsize = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, readsize);
                        downloadCount += readsize;// 时时获取下载到的大小
                        float progress = downloadCount * 1.0f / totalSize;
                        int pr = (int) (progress * 100);

                        //该判断条件是为了下载进度是5的倍数的时候才去更新ui,以免造成ui的卡顿
                        if (preProgress != pr && pr > 0 && pr % 5 == 0) {
                            preProgress = pr;
                            Logger.i("preProgress" + preProgress);
                            Message msg = handler.obtainMessage();
                            msg.what = 3;
                            msg.obj = pr;
                            handler.sendMessage(msg);
                        }
                    }

                    httpURLConnection.disconnect();
                    outputStream.flush();
                    inputStream.close();
                    outputStream.close();

                    Message msg = handler.obtainMessage();
                    msg.what = 0;
                    msg.obj = file;
                    handler.sendMessage(msg);

                    Logger.i(file + " downloadCount：" + downloadCount);
                } else {
                    handler.sendEmptyMessage(1);
                    Logger.i("httpErr:response：" + response);
                }
            } catch (Exception e) {
                handler.sendEmptyMessage(1);
                e.printStackTrace();
            }
        }).start();
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0: // 下载完成，点击安装
                    installAPK((File) msg.obj);
                    showInstallDialog((File) msg.obj);
                    break;
                case 1://下载失败
                    Logger.e("下载失败");
                    break;
                case 2://正在下载
                    break;
                case 3://开始下载,下载中进度
                    int p = (int) msg.obj;
                    mBuilder.setProgress(100, p, false);
                    mNotifyManager.notify(id, mBuilder.build());
                    break;
            }
        }
    };

    private void showInstallDialog(File t) {
        DialogUtil.showReturnTips(mActivity, "", "新版本已下载完成，是否安装", "立即安装", "取消", new DialogSureCancelListenter() {
            @Override
            public void onSureListenter() {
                mNotifyManager.cancel(id);
                startActivity(getInstallIntent(t));
            }

            @Override
            public void onCancelListenter() {

            }
        }, false);
    }

    private void initNotification() {
        mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel mChannel = new NotificationChannel("upgrade", "应用升级", NotificationManager.IMPORTANCE_LOW);
            mNotifyManager.createNotificationChannel(mChannel);
        }

        //设置下载过程中，点击通知栏，回到主界面
        Intent updateIntent = new Intent(mActivity, MainActivity.class);
        updatePendingIntent = PendingIntent.getActivity(mActivity,0,updateIntent,0);

        mBuilder = new NotificationCompat.Builder(mActivity, "upgrade");
        mBuilder.setContentTitle("版本升级")
                .setContentText("下载中，请稍等……")
                .setContentIntent(updatePendingIntent)
                .setSmallIcon(R.mipmap.ic_launcher);
        mBuilder.setProgress(100, 0, false);
        mNotifyManager.notify(id, mBuilder.build());
    }

    /**
     * 点击通知安装apk
     */
    private void installAPK(File t) {
        updatePendingIntent = PendingIntent.getActivity(mActivity, 0, getInstallIntent(t), 0);
        mBuilder.setContentTitle("版本升级")
                .setContentText("下载完成,点击安装。")
                .setContentIntent(updatePendingIntent)
                .setAutoCancel(true)
                .setSmallIcon(R.mipmap.ic_launcher);
        mBuilder.setProgress(0, 0, false);
        mNotifyManager.notify(id, mBuilder.build());
    }

    private Intent getInstallIntent(File t) {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");

        //版本在7.0以上是不能直接通过uri访问的
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
            //参数1:上下文, 参数2:Provider主机地址 和配置文件中保持一致,参数3:共享的文件
            Uri apkUri = FileProvider.getUriForFile(mActivity, "com.yyk.yykywd.fileProvider", t);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(t),
                    "application/vnd.android.package-archive");
        }

        //更新之后需要用户重新登录
        Hawk.put("ISLOGFLAG", LoginActivity.TAG);

        return intent;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }

    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void update() {
        dialog.dismiss();
        initNotification();
        updateAPK(info);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        MainActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void updateRationale(final PermissionRequest request) {
        DialogUtil.showReturnTips(mActivity, "", "需要手机存储权限", "开启权限", "不开启", new DialogSureCancelListenter() {
            @Override
            public void onSureListenter() {
                request.proceed();
            }

            @Override
            public void onCancelListenter() {
                request.cancel();
            }
        }, false);
    }

    @OnNeverAskAgain({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void updateAskAgain() {
        DialogUtil.showReturnTips(mActivity, "", "您已拒绝权限，并不在询问", "开启权限", "不开启", new DialogSureCancelListenter() {
            @Override
            public void onSureListenter() {
                Intent intent = new Intent();
                if (Build.VERSION.SDK_INT >= 9) {
                    intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                    intent.setData(Uri.fromParts("package", mActivity.getPackageName(), null));
                } else if (Build.VERSION.SDK_INT <= 8) {
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
                    intent.putExtra("com.android.settings.ApplicationPkgName", mActivity.getPackageName());
                }
                startActivity(intent);
            }

            @Override
            public void onCancelListenter() {

            }
        }, false);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //将这一行注释掉，阻止activity保存fragment的状态
//        super.onSaveInstanceState(outState);
    }
}
